<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
  <title>TOUPROPRE DBMS</title>
	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" media="screen" type="text/css" title="Design" href="styles/design.css" />
</head>

<body>
    <!-- TITLE  -->
	<div id="page_title">
      <h1>Add Data</h1>
    </div>

    <!-- Side Menues -->
    <?php include "tools/Menues.html"; ?>

    <!-- Main Body -->
    <div id="page_body">
<?php
/*
 * Inclusions:
 */
include "tools/ColumnNames.php";
include "tools/Forms.php";
include "tools/Queries.php";

$nitems = 10;

/*
 * Function Definitions:
 */
// Describes what to do when 
//    NOT isset($_GET['table') AND NOT isset($_POST['submit'])
function ShowTableSelectForm() {
    echo '<p class="text">This page will allow you to add data to the database.</p>';
    echo "\n<p class='text'>Please select a table:</p>";
    echo "\n<form action='add.php' method='get'>";
    echo "\n<select name='table'>";
    echo "\n<option value='clients'>Clients</option>";
    echo "\n<option value='suppliers'>Suppliers</option>";
    echo "\n<option value='items'>Items</option>";
    echo "\n<option value='sales'>Sales</option>";
    echo "\n<option value='purchases'>Purchases</option>";
    echo "\n<option value='facilities'>Facilities</option>";
    echo "\n</select>";
    echo "\n<input type='submit' name='submit' value='Select'>";
    echo "\n</form>";
}

// Describes what to do when 
//    isset($_GET['table') AND NOT isset($_POST['submit'])
function ShowInputForm() {
    switch($_GET['table']) {
    case 'clients':
    case 'suppliers':
    case 'items':
    case 'facilities':
        $cols = GetInputColumnsArray($_GET['table']);
        EchoColumnsForm('add.php?table='.$_GET['table'], 'submit', 'Add', $cols);
        break;
    case 'sales':
        $before = '<br/>Client ID : <input type="text" name="clientID" />'.
            '<br/>Facility ID : <input type="text" name="facilityID" />'.
            '</br/><br/>';
        global $nitems;
        EchoItemListForm('add.php?table=sales',$nitems, $before,'');
        break;
    case 'purchases':
        $before = '<br/>SupplierID ID : <input type="text" name="supplierID" />'.
            '<br/>Facility ID : <input type="text" name="facilityID" />'.
            '</br/><br/>';
        global $nitems;
        EchoItemListForm('add.php?table=purchases',$nitems, $before,'');
        break;
    default:
        return;
    }
}

// Displays a Hyperlink to return to add.php
function ShowSelectTable() {
    echo "<br/><a href=add.php>Select Table</a>";
}

// Displays a Hyperlink to return to add.php?table=
function ShowAddNewEntry() {
    $params="?table=".$_GET['table'];     
    echo " | <a href=add.php".$params.">Add another entry</a>";
}

function GetInputColumnsArray($tablename) {
    if($tablename=='clients') {
        return array('FirstName',
                     'LastName',
                     'VATnum',
                     'Address',
                     'PostCode',
                     'Town',
                     'Country');
    }
    else if($tablename=='suppliers') {
        return array('Name',
                     'VATnum',
                     'Address',
                     'PostCode',
                     'Town',
                     'Country');
    }
    else if($tablename=='items') {
        return array('supplierID',
                     'Name',
                     'Brand',
                     'Descrip',
                     'Capacity',
                     'BarCode',
                     'SellCost',
                     'BuyCost',
                     'VATrate',
                     'Active');
    }
    else if($tablename=='sales') {
        return array('clientID', 
                     'facilityID');
    }
    else if($tablename=='purchases') {
        return array('supplierID',
                     'facilityID');
    }
    else if($tablename=='facilities') {
        return array('Name',
                     'Address',
                     'PostCode',
                     'Town',
                     'Country');
    }
    else {
        echo "<p class=text>Unknown table.</p>";
    }
}

function additionalCols() {
    switch($_GET['table']) {
    case 'clients': 
        return ', DateAdded';
    case 'suppliers':
        return ', DateAdded, BankRupt';
    case 'sales':
    case 'purchases':
        return ', datetime';
    case 'items':
    case 'facilityID':
    default: 
        return '';
    }
}

function additionalVals() {
    switch($_GET['table']) {
    case 'clients': 
        return ', CURDATE()';
    case 'suppliers':
        return ', CURDATE(), 0';
    case 'sales':
    case 'purchases':
        return ', CURDATE()*1000000+CURTIME()';
    case 'items':
    case 'facilityID':
    default: 
        return '';
    }
}

// Describes what to do when 
//    isset($_GET['table') AND isset($_POST['submit'])
function add() {
    $cols = GetInputColumnsArray($_GET['table']);
    $listcols = arrayCommaString($cols,false).additionalCols();
    $listvals = postArrayCommaString($cols,true).additionalVals();
    $sql = 'INSERT INTO '.
        $_GET['table'].'('.$listcols.') VALUES('.$listvals.')';

    switch($_GET['table']) {
        /*************************************
         * Add procedure for "sales"
         *************************************/
    case 'sales':
        // TODO : check there's atleast 1 item sold
        global $nitems;
        $stock_ok=TRUE;

        // Check presence of clientID and facility ID
        if(!isset($_POST['clientID']) OR !isset($_POST['facilityID']))  {
            echo "<p class=sql_error>You must the specify client and facility ID.</p>";
            return;
        }

        // Check stock :
        for($i=0; $i<$nitems; $i++) {
            if(isset($_POST['item'.$i]) AND 
               isset($_POST['qty'.$i])  AND
               $_POST['item'.$i] != ''  AND
               $_POST['qty'.$i]  != '') {
                $r= WithdrawStockFromFacility($_POST['item'.$i],
                                              $_POST['qty'.$i],
                                              $_POST['facilityID']);
                if($r != FALSE) {
                    $cost[$i] = $r ;
                }
                else {
                    $stock_ok = FALSE;
                }
            }
        }
        if(!$stock_ok) {return;}

        // Stock is ok. Add the sales record :
        $id = EchoInsertQuery($sql,$_GET['table']);

        // Add the sold items.
        include "tools/connect.php";
        echo "\n\n<table frame=box>\n<tr bgcolor=#000077>";
        echo "\n<td><font color=#ffffff>isalesID</font></td>";
        echo "\n<td><font color=#ffffff>salesID</font></td>";
        echo "\n<td><font color=#ffffff>itemID</font></td>";
        echo "\n<td><font color=#ffffff>qty</font></td>";
        echo "\n<td><font color=#ffffff>cost</font></td>";
        echo "\n</tr>";
        for($i=0; $i<$nitems; $i++) {
            if(isset($_POST['item'.$i]) AND 
               isset($_POST['qty'.$i])  AND
               $_POST['item'.$i] != ''  AND
               $_POST['qty'.$i]  != '') {
                // Add the entry:
                $listvals = $id.', "'.$_POST['item'.$i].'", '.$_POST['qty'.$i].', '.$cost[$i];
                $sql = 'INSERT INTO '.
                    'itemsSold(salesID, itemID, qty, cost)'.
                    'VALUES('.$listvals.')';
                $response = mysql_query($sql);

                // Display the entry:
                $sql = 'SELECT * FROM itemsSold '.
                    'WHERE isalesID='.mysql_insert_id();
                $response = mysql_query($sql);
                $row = mysql_fetch_row($response);
                $n = count($row);
                echo "\n<tr>";
                for($j=0; $j<$n; $j++) {
                    echo "\n<td>".$row[$j]."</td>";
                }
                echo "\n</tr>";
            }
        }
        echo "\n<table>";
        mysql_close();
        break;
        
        /*************************************
         * Add procedure for "purchases"
         *************************************/
    case 'purchases':
        // TODO : check there's atleast 1 item purchased
        global $nitems;

        // Check presence of supplierID and facility ID
        if(!isset($_POST['supplierID']) OR !isset($_POST['facilityID']))  {
            echo "<p class=sql_error>You must the specify supplier and facility ID.</p>";
            return;
        }

        // Add the purchase record :
        $id = EchoInsertQuery($sql,$_GET['table']);

        // Add the purchased items.
        echo "\n\n<table frame=box>\n<tr bgcolor=#000077>";
        echo "\n<td><font color=#ffffff>ipurchaseID</font></td>";
        echo "\n<td><font color=#ffffff>purchaseID</font></td>";
        echo "\n<td><font color=#ffffff>itemID</font></td>";
        echo "\n<td><font color=#ffffff>qty</font></td>";
        echo "\n<td><font color=#ffffff>cost</font></td>";
        echo "\n</tr>";
        for($i=0; $i<$nitems; $i++) {
            if(isset($_POST['item'.$i]) AND 
               isset($_POST['qty'.$i])  AND
               $_POST['item'.$i] != ''  AND
               $_POST['qty'.$i]  != '') {
                // Update Stock :
                AddStockToFacility($_POST['item'.$i],$_POST['qty'.$i],$_POST['facilityID']);
                
                // Get Cost :
                include "tools/connect.php";
                $sql = "SELECT BuyCost FROM items WHERE itemID='".$_POST['item'.$i]."'";

                $response= mysql_query($sql);
                if(!$response) {echo mysql_error(); mysql_close(); return;}

                $row = mysql_fetch_row($response);
                if(!$row) {echo '<p class=sql_error>Item not found.</p>'; mysql_close(); return;}

                $cost = $_POST['qty'.$i] * $row[0];

                // Add the entry :
                $listvals = $id.', "'.$_POST['item'.$i].'", '.$_POST['qty'.$i].', '.$cost;
                $sql = 'INSERT INTO '.
                    'itemsPurchased(purchaseID, itemID, qty, cost) '.
                    'VALUES('.$listvals.')';
                
                $response = mysql_query($sql);
                if(!$response) {echo mysql_error();}

                // Display the entry :
                $sql = 'SELECT * FROM itemsPurchased '.
                    'WHERE ipurchaseID='.mysql_insert_id();
                $response = mysql_query($sql);
                $row = mysql_fetch_row($response);
                $n = count($row);
                echo "\n<tr>";
                for($j=0; $j<$n; $j++) {
                    echo "\n<td>".$row[$j]."</td>";
                }
                echo "\n</tr>";
                mysql_close();
            }
        }
        echo "\n<table>";
        
        break;

        /*****************************************************************
         * Add procedure for "clients", "suppliers", "items", facilities:
         *****************************************************************/
    default:
        EchoInsertQuery($sql,$_GET['table']);;
    }
}


/*
 * Behaviour :
 *
 * @note Things to modify to add a table:
 *
 *  ** update GetInputColumnsArray()
 *  ** update additionalCols and additionalVals
 *  ** update table selection form - ShowTableSelectForm()
 *  ** update ShowInputForm()
 *  ** update add()

 *  
 */
if(isset($_GET['table'])) {

    if( isset($_POST['submit']) ) {
        add();
        ShowSelectTable(); ShowAddNewEntry();
    }

    else {
        ShowInputForm();
        ShowSelectTable(); 
    }
 }
 else {
     ShowTableSelectForm();
 }
?>
    </div>
    
    <!-- Footer -->
    <?php include "tools/Footer.html"; ?>
</body>
</html>
